package com.itheima.interceptors;

import com.itheima.utils.AccessLimit;
import com.itheima.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 自定义拦截器
 * @Date :2019-08-17 09:49
 * @Author : yuan_he_song
 */
@Component
public class JwtInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override /** 前置拦截器 */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod){
            HandlerMethod mh = (HandlerMethod) handler;
            Method method = mh.getMethod();
            if (!method.isAnnotationPresent(AccessLimit.class)){
                return true; // 不是限流的注解直接放行
            }
            AccessLimit accessLimit = method.getAnnotation(AccessLimit.class);
            if (accessLimit == null){
                return true; // 没有限流的注解直接放行
            }

            int limit = accessLimit.limit();
            int seconds = accessLimit.seconds();
            String key = request.getRequestURI();
            Long maxLimit = redisTemplate.opsForValue().increment(key);
            if (maxLimit == 1){ // 第一次请求接口
                redisTemplate.boundValueOps(key).expire(seconds, TimeUnit.SECONDS);
            } else if (maxLimit > limit){
                throw new RuntimeException("请求太频繁, 稍后再试!");
            }
        }
        /** 1.获取头信息 */
//        String token = request.getHeader("Authorization");
//        if(StringUtils.isNotEmpty(token)){
//            // 解析token 获取claims
//            Claims claims = jwtUtils.parseToken(token);
//            if(claims != null){
//                String info = claims.getId() +"-"+ claims.getSubject();
//                redisTemplate.boundValueOps("currentUser").set(info,30, TimeUnit.MINUTES);
//                return true;
//            }
//        }else {
//            ThrowException.cast(MsgCode.TOKEN_NULL);
//            return false;
//        }
        return true;
    }

}
